package org.lmind.example.common.web;

import java.util.List;
import java.util.regex.Matcher;

import org.lmind.example.common.core.Properties;
import org.lmind.example.common.web.internal.ResourcePattern;
import org.lmind.example.util.text.PlaceholderResolver;
import org.lmind.example.util.text.PlaceholderResolver.Resolver;

public class GeneralWebResourceResolver implements UrlResolver {
	
	private List<ResourcePattern> patterns;
	
	private PlaceholderResolver placeholderResolver = new PlaceholderResolver();
	
	private Properties properties;
	
	public List<ResourcePattern> getPatterns() {
		return patterns;
	}

	public void setPatterns(List<ResourcePattern> patterns) {
		this.patterns = patterns;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	@Override
	public String resolveUrl(String resource) {
		
		for (ResourcePattern pattern : patterns) {
			Matcher matcher = pattern.getPattern().matcher(resource);
			if (!matcher.find())
				continue;
			
			Resolver resolver = placeholderResolver.resolver(pattern.getTemplate());
			while (resolver.next()) {
				if (properties.getValue(resolver.getKey()) != null) {
					resolver.replace((String)properties.getValue(resolver.getKey()));
				} else {
					int num = 0;
					try {
						num = Integer.parseInt(resolver.getKey());
					} catch (NumberFormatException e) {
						break;
					}
					if (num <= matcher.groupCount()) {
						resolver.replace(matcher.group(num));
					}
				}
				
			}
			return resolver.build();
		}
		
		// 如果没有匹配的模式,则返回原字符串
		return resource;
	}

}
